//
//  THPhotoController.m
//  THImageEditDemo
//
//  Created by 谭簧 on 2018/5/5.
//  Copyright © 2018年 Tan.huang. All rights reserved.
//

#import "THPhotoController.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import <TZImagePickerController/TZImagePickerController.h>
#import "THAssetCell.h"
#import "THImageEditViewController.h"


@interface THPhotoController () <UICollectionViewDelegate, UICollectionViewDataSource, SDCycleScrollViewDelegate>
{
    UIButton *_progressHUD;
    UIView *_HUDContainer;
    UIActivityIndicatorView *_HUDIndicatorView;
    UILabel *_HUDLabel;
}
@property (nonatomic, weak) SDCycleScrollView *scrollView;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIButton *cancelBtn;
@property (nonatomic, strong) NSMutableArray *photoArr;
@property (nonatomic, strong) NSMutableArray *photoNames;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;

@property (nonatomic, assign) int32_t imageRequestID;
@property (nonatomic, assign) NSInteger scrollViewIndex;

@end

@implementation THPhotoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self configData];
    [self configTitleView];
    [self fetchAssetModels];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)configData {
    self.photoArr = [NSMutableArray array];
    self.selectedAssets = [NSMutableArray array];
    self.selectedPhotos = [NSMutableArray array];
    self.photoNames = [NSMutableArray array];
}

- (void)configTitleView {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, 300, 44)];
    [btn setTitle:self.model.name forState:UIControlStateNormal];
    
}

- (void)configView {
    [self hideProgressHUD];
    CGFloat top = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat width = self.view.frame.size.width;
    CGFloat itemWidth = (width - 3) / 3;
    SDCycleScrollView *scrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, top, width, width - itemWidth)];
    scrollView.infiniteLoop = NO;
    scrollView.autoScroll = NO;
    scrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionHeadersPinToVisibleBounds = YES;
    flowLayout.minimumLineSpacing = 1.5;
    flowLayout.minimumInteritemSpacing = 1.5;
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 44);  //设置headerView大小
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(scrollView.frame), width, self.view.frame.size.height - CGRectGetMaxY(scrollView.frame) - 44) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    [collectionView registerClass:[THAssetCell class] forCellWithReuseIdentifier:@"THAssetCell"];
    [collectionView registerClass:[THPhotoHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"THPhotoHeaderView"];
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(width - 100, self.view.frame.size.height - 44, 100, 44)];
    [cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    self.cancelBtn = cancelBtn;
    
    /// 默认选择第一个
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self collectionView:self.collectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    });
}


- (void)showProgressHUD {
    if (!_progressHUD) {
        _progressHUD = [UIButton buttonWithType:UIButtonTypeCustom];
        [_progressHUD setBackgroundColor:[UIColor clearColor]];
        
        _HUDContainer = [[UIView alloc] init];
        _HUDContainer.layer.cornerRadius = 8;
        _HUDContainer.clipsToBounds = YES;
        _HUDContainer.backgroundColor = [UIColor darkGrayColor];
        _HUDContainer.alpha = 0.7;
        
        _HUDIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        
        _HUDLabel = [[UILabel alloc] init];
        _HUDLabel.textAlignment = NSTextAlignmentCenter;
        _HUDLabel.text = @"load...";
        _HUDLabel.font = [UIFont systemFontOfSize:15];
        _HUDLabel.textColor = [UIColor whiteColor];
        
        [_HUDContainer addSubview:_HUDLabel];
        [_HUDContainer addSubview:_HUDIndicatorView];
        [_progressHUD addSubview:_HUDContainer];
    }
    [_HUDIndicatorView startAnimating];
    [[UIApplication sharedApplication].keyWindow addSubview:_progressHUD];
    
    // if over time, dismiss HUD automatic
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf hideProgressHUD];
    });
}

- (void)hideProgressHUD {
    if (_progressHUD) {
        [_HUDIndicatorView stopAnimating];
        [_progressHUD removeFromSuperview];
    }
}


- (void)fetchAssetModels {
    [self showProgressHUD];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[TZImageManager manager] getAssetsFromFetchResult:self->_model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
            [self->_photoArr addObject:[NSMutableArray arrayWithArray:models]];
            if (self.photoArr.count > 1) {
                [self.photoNames addObject:self.model.name];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self configView];
            });
        }];
    });
}

#pragma mark - UICollectionViewDelegate and UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return  self.photoArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.photoArr[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZAssetModel *model = self.photoArr[indexPath.section][indexPath.item];
    THAssetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"THAssetCell" forIndexPath:indexPath];
    cell.model = model;
    return cell;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    THPhotoHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"THPhotoHeaderView" forIndexPath:indexPath];
    headerView.name = self.photoNames.count > 0 ? self.photoNames[indexPath.section] : @"";
    [headerView setImgEditBtnClickBlock:^{
        THImageEditViewController *editVC = [[THImageEditViewController alloc] initWithImage:self.selectedPhotos[self.scrollViewIndex]];
        [self.navigationController pushViewController:editVC animated:YES];
    }];
    return headerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    TZAssetModel *model = self.photoArr[indexPath.section][indexPath.item];
    // 1. cancel select / 取消选择
    if (model.isSelected) {
        if (self.selectedPhotos.count == 1) {
            return;
        }
        model.isSelected = NO;
        for (int i = 0; i < self.selectedAssets.count; i ++) {
            TZAssetModel *model_item = self.selectedAssets[i];
            if ([[[TZImageManager manager] getAssetIdentifier:model.asset] isEqualToString:[[TZImageManager manager] getAssetIdentifier:model_item.asset]]) {
                [self.selectedAssets removeObject:model_item];
                [self.selectedPhotos removeObjectAtIndex:i];
                break;
            }
        }
        self.scrollView.localizationImageNamesGroup = self.selectedPhotos;
        [self scrollViewSlide];
    } else {
        model.isSelected = YES;
        [self.selectedAssets addObject:model];
        [self fetchBigImage:model.asset];
    }
    [collectionView reloadItemsAtIndexPaths:@[indexPath]];
}


- (void)fetchBigImage:(PHAsset *)asset {
    [self showProgressHUD];
    if (self.imageRequestID) {
        [[PHImageManager defaultManager] cancelImageRequest:self.imageRequestID];
    }
    self.imageRequestID = [[TZImageManager manager] getPhotoWithAsset:asset photoWidth:self.view.frame.size.width completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
        [self hideProgressHUD];
        if (!isDegraded) {
            [self.selectedPhotos addObject:photo];
            self.scrollView.localizationImageNamesGroup = self.selectedPhotos;
            [self scrollViewSlide];
            self.imageRequestID = 0;
        }
    }];
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
    NSLog(@"didScrollToIndex === %ld", index);
    self.scrollViewIndex = index;
}

- (void)scrollViewSlide {
    if (self.selectedPhotos.count == 0) {
        return;
    }
    for (UIView *view in self.scrollView.subviews) {
        if ([view isKindOfClass:[UICollectionView class]]) {
            self.scrollViewIndex = self.selectedPhotos.count - 1;
            UICollectionView *collectionView = (UICollectionView *)view;
            NSIndexPath *path = [NSIndexPath indexPathForItem:self.selectedPhotos.count - 1 inSection:0];
            [collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            break;
        }
    }
}

- (void)cancelBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
